package com.zhu.storesmanager;


import java.text.SimpleDateFormat;

import com.zhu.storesmanager.models.UserData;
import com.zhu.storesmanager.network.DownloadService;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.PreferenceKeys;
import com.zhu.storesmanager.utils.PreferenceStore;
import com.zhu.storesmanager.utils.SalesData;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

/**
 * 主界面
 */
public class MainActivity extends Activity implements View.OnClickListener{

	private TextView mStoreInfoView = null; //顶部门店信息
	int[] mTempArray = new int[2];
	private boolean isAutoGotoRemind = false; //是否自动跳转

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main); //设置显示界面

		setupView();
		initData();

		if(!gotoRemindActivity()){
			if(DataUtils.mUserData.isNeedUpdate){ //需要升级APK
				Actions.popUpdateDialog(this);
			}
		}
	}

	/**
	 * 初始化view
	 */
	private void setupView(){
		findViewById(R.id.main_exit).setOnClickListener(this);
		mStoreInfoView = (TextView)findViewById(R.id.main_storeinfo);
		if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SALESPERSON){ //是促销员则显示门店
		    mStoreInfoView.setText(DataUtils.mUserData.mCounterTarget + "-" + DataUtils.mUserData.mCounterName);
		}else{
		    mStoreInfoView.setVisibility(View.INVISIBLE);
		}

		setupAllButtonView(DataUtils.mUserData.mRoleType);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		if(DataUtils.mUserData.mRoleType == UserData.USERTYPE_SALESPERSON){
			SalesData.getInstance(this);//加载促销员销量数据
			clearHistoryData();
		}
	}

	/**
	 * 根据用户类别设置不同的界面
	 * @param type 用户类别
	 */
	private void setupAllButtonView(int type){
		int status  = DataUtils.getDataButton(type, 1, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button1), mTempArray);
		}
		status  = DataUtils.getDataButton(type, 2, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button2), mTempArray);
		}
		status  = DataUtils.getDataButton(type, 3, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button3), mTempArray);
		}
		status  = DataUtils.getDataButton(type, 4, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button4), mTempArray);
		}
		status  = DataUtils.getDataButton(type, 5, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button5), mTempArray);
		}
		status  = DataUtils.getDataButton(type, 6, mTempArray);
		if(status == 1){
			setButtonView((TextView)findViewById(R.id.main_button6), mTempArray);
		}
	}

	/**
	 * 设置button内容
	 * @param view 界面
	 * @param array 数据
	 */
	private void setButtonView(TextView view , int[] array){
		view.setOnClickListener(this);
		view.setText(mTempArray[0]);
		view.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(mTempArray[1]), null, null);
	}

	/**
	 * 点击事件处理 
	 * @param arg0 界面的view
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.main_exit: //退出
						popExitDialog();
					break;
				case R.id.main_button1: //菜单1
					doClickButton(DataUtils.mUserData.mRoleType, 1);
					break;
				case R.id.main_button2: //菜单2
					doClickButton(DataUtils.mUserData.mRoleType, 2);
					break;
				case R.id.main_button3: //菜单3
					doClickButton(DataUtils.mUserData.mRoleType, 3);
					break;
				case R.id.main_button4: //菜单4
					doClickButton(DataUtils.mUserData.mRoleType, 4);
					break;
				case R.id.main_button5: //菜单5
					doClickButton(DataUtils.mUserData.mRoleType, 5);
					break;
				case R.id.main_button6: //菜单6
					doClickButton(DataUtils.mUserData.mRoleType, 6);
					break;
			}
		}
	}

	/**
	 * @param type 账号类型
	 * @param buttonId 按钮ID
	 */
	private void doClickButton(int type, int buttonId){
		Intent intent = new Intent();
		if(type == UserData.USERTYPE_SALESPERSON){//促销员
			switch(buttonId){
				case 1: //签到
				    if(DataUtils.mUserData.isOffline){//检测是否离线模式登录
                        Actions.toastShort(this, getString(R.string.offlineloginnotsync));
                        return;
                    }
					intent.setClass(this, SalespersonSigninActivity.class);
					this.startActivity(intent);
				break;
				case 2://提醒
					intent.setClass(this, RemindListActivity.class);
					this.startActivity(intent);
					break;
				case 3: //同步
					if(DataUtils.mUserData.isOffline){//检测是否离线模式登录
						Actions.toastShort(this, getString(R.string.offlineloginnotsync));
						return;
					}
					intent.setClass(this, SyncActivity.class);
					this.startActivity(intent);
					break;
				case 4: //销量上报
					intent.setClass(this, SalesReportActivity.class);
					this.startActivity(intent);
					break;
				case 5://上报查询
					intent.setClass(this, SalesPutInquiryActivity.class);
					this.startActivity(intent);
					break;
				case 6://销售员特殊任务
					intent.setClass(this, SpecialTaskActivity.class);
					this.startActivity(intent);
					break;
			}
		}else if(type == UserData.USERTYPE_SUPERVISOR){ //督导
		    switch(buttonId){
                case 1: //拜访
                    intent.setClass(this, SvVisitTaskActivity.class);
                    this.startActivity(intent);
                    break;
                case 2://提醒
                    intent.setClass(this, RemindListActivity.class);
                    this.startActivity(intent);
                    break;
                case 3: //同步
                    if(DataUtils.mUserData.isOffline){//检测是否离线模式登录
                        Actions.toastShort(this, getString(R.string.offlineloginnotsync));
                        return;
                    }
                    intent.setClass(this, SyncActivity.class);
                    this.startActivity(intent);
                    break;
		    }
		}else if(type == UserData.USERTYPE_ADMIN){ //管理员
			switch (buttonId) {
				case 1: //查询
					if(DataUtils.mUserData.isOffline){//检测是否离线模式登录
                        Actions.toastShort(this, getString(R.string.offlineloginnotsync));
                        return;
                    }
					intent.setClass(this, AdminSearchActivity.class);
					this.startActivity(intent);
					break;
			}
		}
	}

	 /**
     * 退出提示框
     * 
     */
    private void popExitDialog() {
        Actions.alertShowDetails(this, getString(R.string.exitclew),
                getString(R.string.exitcontent),
                R.string.button_ok, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        finish();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    /**
     * 清空昨天的历史数据
     */
    private void clearHistoryData(){
    	long loginTime = PreferenceStore.getInstance(this).getLong(PreferenceKeys.KEY_LASTLONGINTIME, 0);
        long timeMillis = System.currentTimeMillis();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String sp_time = sf.format(loginTime);
        String current_time = sf.format(timeMillis);
        if(!sp_time.equals(current_time)){ // 不同一天 
            Log.d("clearHistoryData");
            SalesData.getInstance(this).clearAllData(); //清除销量数据
            getContentResolver().delete(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除签到数据
            PreferenceStore.getInstance(this).putLong(PreferenceKeys.KEY_LASTLONGINTIME, System.currentTimeMillis());
        }
    }

    /**
     * 跳转提醒界面
     */
    private boolean gotoRemindActivity(){
    	if(DatabaseUtil.hasRemindData(this)){
    		isAutoGotoRemind = true;
    		Intent intent = new Intent();
    		intent.putExtra("showupdate", true);
    		intent.setClass(this, RemindListActivity.class);
            this.startActivity(intent);
    	}
    	return isAutoGotoRemind;
    }
}
